import { useLocation, useNavigate } from "react-router-dom"
import { FuncVoid } from "../types"
import { useEffect, useState } from "react"
import moment from "moment"

// 页面跳转
export const useCommonFunc = () => {
    const router:any = useNavigate()
    const { pathname }  = useLocation()

    const gotopage = (url:string|number) => {
        router(url)
    }

    const hasUrl = (url:string)=>{
        return pathname.indexOf(url) > -1 ? true : false  // 
    }

    const dateFormat = (date:any,type='YYYY-MM-DD')=>{
        return moment(date).format(type)
    }

    return{
        gotopage,
        hasUrl,
        dateFormat
    }
}

// 倒计时
export const useTimeDown = (timing:number,onEnd:FuncVoid) => {
    let [count,setcount] = useState(timing)
    let timer = null as any
    const start:any = () =>{
        timer = setInterval(()=>{
            if(count>0){
                setcount(--count)
            }else{
                clearInterval(timer)
                timer = null
                onEnd()
            }
        },1000)
    }

    useEffect(()=>{
        return()=>{
            clearInterval(timer)
            timer = null
        }
    },[])

    return[
        count,
        start,
    ]
}


// 当前周是今年的第几周 
export const useGetYearWeek  = ():number[]=>{
    // const [week,setWeek] = useState(0);
    var time = new Date()
    var a = time.getFullYear()
    var b = time.getMonth() + 1;
    var c = time.getDate()

    var date1 = new Date(a, parseInt(b) - 1, c),    // 今天的时间戳
    date2 = new Date(a, 0, 1),   // 今年1月1号的 时间戳 
    d = Math.round((date1.valueOf() - date2.valueOf()) / 86400000);  // 判断多少天 
    // return [
    //     Math.ceil((d + (date2.getDay() + 1 - 1)) / 7) 
    // ]

    console.log(date2.getDay())
    // return [Math.floor(d/7) + (date2.getDay() == 0 ? 1 :0) ]
    return [ Math.ceil(d/7) + (date2.getDay()==0 ? 0 : 1 ) ]
}
